package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Category;
import com.itheima.goods.service.CategoryService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author cai xu dong
 * @date 2021/5/9 20:17
 */
@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping
    public Result findAll() {
        List<Category> list = categoryService.list();
        return new Result(true, 20000, "查询成功", list);
    }
    @PostMapping
    public Result add(@RequestBody Category c) {
        categoryService.save(c);
        return new Result(true,20000,"增加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result search(@PathVariable("page") Long current, @PathVariable("size") Long size) {
        Page<Category> Page = new Page<>(current, size);
        categoryService.page(Page);
        return new Result(true, 20000, "查询成功", Page);
    }

    @PostMapping("search2/{page}/{size}")
    public Result search2(@PathVariable("page") Long current, @PathVariable("size") Long size,
                          @RequestBody Map<String, String> searchMap) {
        Page<Category> pages = new Page<>(current, size);
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery();
        wrapper.eq(Category::getId,searchMap.get("id"));
        wrapper.like(Category::getName,searchMap.get("name"));
        Page<Category> page = categoryService.page(pages, wrapper);
        return new Result(true,20000,"查询成功",page);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable int id) {
        Category category = categoryService.getById(id);
        return new Result(true, 20000, "查询成功", category);
    }
    @PutMapping("/{id}")
    public Result update(@PathVariable("id") int id,@RequestBody Category category){
        LambdaQueryWrapper<Category> wrapper = Wrappers.<Category>lambdaQuery();
        LambdaQueryWrapper<Category> eq = wrapper.eq(Category::getId, id);
        boolean update = categoryService.update(category, eq);
        return new Result(true,20000,"更新成功",update);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int id) {
        categoryService.removeById(id);
        return new Result(true, 20000, "删除成功");
    }
}
